//
//  CHBubbleView.h
//  WZEfengAndEtong
//
//  Created by 李旭 on 16/8/11.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "CHBubbleView.h"
#import "MicroDef.h"
#import "NSString+CHChatView.h"
#import "UIImage+CHChatView.h"
#import "CBEmotionView.h"
#import <QuartzCore/QuartzCore.h>
#import "UIUtil.h"

#define kMarginTop 10.0f
#define kMarginBottom 10.0f
#define kPaddingTop 8.0f
#define kPaddingBottom 8.0f
#define kBubblePaddingRight 28.0f

#define TEXTLABEL_MARGININSET1 15
#define TEXTLABEL_MARGININSET2 20



@interface CHBubbleView ()<MutiltimediaViewDelegate>
- (void)setup;
@end

@implementation CHBubbleView

@synthesize isNotice;
@synthesize pictureView;
@synthesize voiceView;
@synthesize fileView;
@synthesize type;
@synthesize videoView;
@synthesize redpacketView;
@synthesize style;
@synthesize text;
@synthesize textLabel;
@synthesize img_voice;
@synthesize selectedToShowCopyMenu;
@synthesize backgroundImageView;
@synthesize foregroundImageView;


- (void)dealloc
{
//    NSLog(@"CHBubbleView dealloc");
}

#pragma mark - Initialization
- (id)initWithFrame:(CGRect)rect
         bubbleType:(CHBubbleMessageType)bubleType
        bubbleStyle:(CHBubbleStyle)bubbleStyle
           isNotice:(BOOL)flag
{
    self = [super initWithFrame:rect];
    if(self) {
        self.type = bubleType;
        self.style = bubbleStyle;
        self.isNotice = flag;
        [self setup];
    }
    return self;
}

#pragma mark - Setup
- (void)setup
{
    self.backgroundColor = [UIColor clearColor];
    backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    if (self.style == CHBubbleStyleText) {
        UIImage *image = [self bubbleImageWithStyle:CHBubbleStyleText];
        [backgroundImageView setImage:image];
        backgroundImageView.backgroundColor = ClearColor;
        [self sendSubviewToBack:backgroundImageView];
        [self addSubview:backgroundImageView];
    }
    if (self.style == CHBubbleStyleVoice) {
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, 20, 47);
        if (self.type == CHBubbleMessageTypeSended) {
            self.frame = CGRectMake(HARDWARE_SCREEN_WIDTH - kCHAvatarSize - 2*INSET_WIDTH-self.frame.size.width, self.frame.origin.y, 20, 47);
        }
        
        voiceView = [[MutiltimediaView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        [voiceView setBackgroundColor:[UIColor clearColor]];
        
        UIImage *image = [self bubbleImageWithStyle:CHBubbleStyleVoice];
        [backgroundImageView setImage:image];
//        backgroundImageView.backgroundColor = BlackColor;
        backgroundImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        
        if (self.type == CHBubbleMessageTypeSended) {
            voiceView.voiceType = CHSVoiceTypeSended;
        }
        if (self.type == CHBubbleMessageTypeReceived) {
            if(self.isNotice){
                voiceView.voiceType = CHSVoiceNoticeTypeReceived;
            }else{
                voiceView.voiceType = CHSVoiceTypeReceived;
            }
        }
        [self addSubview:backgroundImageView];
        [self sendSubviewToBack:backgroundImageView];
        [self addSubview:voiceView];
    }
    if (self.style == CHBubbleStylePicture) {
        self.frame = CGRectMake(self.frame.origin.x,
                                self.frame.origin.y,
                                BUBBLEVIEW_PIC_SIZE + 4,
                                BUBBLEVIEW_PIC_SIZE);
        
        if (self.type == CHBubbleMessageTypeSended) {
            self.frame = CGRectMake(HARDWARE_SCREEN_WIDTH - kCHAvatarSize - 2*INSET_WIDTH-self.frame.size.width,
                                    self.frame.origin.y,
                                    BUBBLEVIEW_PIC_SIZE + 4,
                                    BUBBLEVIEW_PIC_SIZE);
        }
        
        pictureView = [[MutiltimediaView alloc] initWithFrame:CGRectMake(0, 0, BUBBLEVIEW_PIC_SIZE, BUBBLEVIEW_PIC_SIZE)];
        pictureView.multiDelegate = self;
        pictureView.frame = CGRectMake(4.0f, 0, BUBBLEVIEW_PIC_SIZE, BUBBLEVIEW_PIC_SIZE);
        if (self.type == CHBubbleMessageTypeSended) {
            pictureView.frame = CGRectMake(0, 0, BUBBLEVIEW_PIC_SIZE, BUBBLEVIEW_PIC_SIZE);
        }

        pictureView.isFromChat = YES;
        [pictureView.layer setCornerRadius:3.0f];
        pictureView.clipsToBounds = YES;
        UIImage *image = [self bubbleImageWithStyle:CHBubbleStylePicture];
        [backgroundImageView setImage:image];
        backgroundImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        [self addSubview:backgroundImageView];
        [self addSubview:pictureView];
        
        
    }
    if (self.style == CHBubbleStyleRedPacket) {
        self.frame = CGRectMake(self.frame.origin.x,
                                self.frame.origin.y,
                                BUBBLEVIEW_PIC_SIZE + 140,
                                BUBBLEVIEW_PIC_SIZE);
        
        if (self.type == CHBubbleMessageTypeSended) {
            self.frame = CGRectMake(HARDWARE_SCREEN_WIDTH - kCHAvatarSize - 2*INSET_WIDTH-self.frame.size.width,
                                    self.frame.origin.y,
                                    BUBBLEVIEW_PIC_SIZE + 140,
                                    BUBBLEVIEW_PIC_SIZE);
        }
        redpacketView = [[MutiltimediaView alloc] initWithFrame:CGRectMake(0, 0, BUBBLEVIEW_PIC_SIZE + 140, BUBBLEVIEW_PIC_SIZE)];
        redpacketView.center = CGPointMake(self.frame.size.width/2+3.5, self.frame.size.height/2);
        if (self.type == CHBubbleMessageTypeSended) {
            redpacketView.center = CGPointMake(self.frame.size.width/2-3.5, self.frame.size.height/2);
        }
        
        redpacketView.isFromChat = YES;
        
        //        [fileView setBackgroundColor:[UIColor lightGrayColor]];
        [redpacketView.layer setCornerRadius:12.0f];
        redpacketView.clipsToBounds = YES;
        UIImage *image = [self bubbleImageWithStyle:CHBubbleStyleRedPacket];
        [backgroundImageView setImage:image];
        backgroundImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        [self addSubview:backgroundImageView];
        [self addSubview:redpacketView];

    }
    if (self.style == CHBubbleStyleVideo) {
        self.frame = CGRectMake(self.frame.origin.x,
                                self.frame.origin.y,
                                BUBBLEVIEW_PIC_SIZE + 4,
                                BUBBLEVIEW_PIC_SIZE);

        if (self.type == CHBubbleMessageTypeSended) {
            self.frame = CGRectMake(HARDWARE_SCREEN_WIDTH - kCHAvatarSize - 2*INSET_WIDTH-self.frame.size.width,
                                    self.frame.origin.y,
                                    BUBBLEVIEW_PIC_SIZE + 4,
                                    BUBBLEVIEW_PIC_SIZE);
        }
        
        videoView = [[MutiltimediaView alloc] initWithFrame:CGRectMake(0, 0, BUBBLEVIEW_PIC_SIZE, BUBBLEVIEW_PIC_SIZE)];
        videoView.multiDelegate = self;
        videoView.frame = CGRectMake(4.0f, 0, BUBBLEVIEW_PIC_SIZE, BUBBLEVIEW_PIC_SIZE);
        if (self.type == CHBubbleMessageTypeSended) {
            pictureView.frame = CGRectMake(0, 0, BUBBLEVIEW_PIC_SIZE, BUBBLEVIEW_PIC_SIZE);
        }
        
        videoView.isFromChat = YES;
        
        //        [pictureView setBackgroundColor:[UIColor lightGrayColor]];
        [videoView.layer setCornerRadius:10.0f];
        videoView.clipsToBounds = YES;
        [self addSubview:videoView];
        
        
    }

    if (self.style == CHBubbleStyleFile) {
        self.frame = CGRectMake(self.frame.origin.x,
                                self.frame.origin.y,
                                BUBBLEVIEW_PIC_SIZE + 140,
                                BUBBLEVIEW_PIC_SIZE);
        
        if (self.type == CHBubbleMessageTypeSended) {
            self.frame = CGRectMake(HARDWARE_SCREEN_WIDTH - kCHAvatarSize - 2*INSET_WIDTH-self.frame.size.width,
                                    self.frame.origin.y,
                                    BUBBLEVIEW_PIC_SIZE + 140,
                                    BUBBLEVIEW_PIC_SIZE);
        }
        
        fileView = [[MutiltimediaView alloc] initWithFrame:CGRectMake(0, 0, BUBBLEVIEW_PIC_SIZE + 140, BUBBLEVIEW_PIC_SIZE)];
        fileView.center = CGPointMake(self.frame.size.width/2+3.5, self.frame.size.height/2);
        if (self.type == CHBubbleMessageTypeSended) {
            fileView.center = CGPointMake(self.frame.size.width/2-3.5, self.frame.size.height/2);
        }
        
        fileView.isFromChat = YES;
        
//        [fileView setBackgroundColor:[UIColor lightGrayColor]];
        [fileView.layer setCornerRadius:12.0f];
        fileView.clipsToBounds = YES;
        UIImage *image = [self bubbleImageWithStyle:CHBubbleStyleFile];
        [backgroundImageView setImage:image];
        backgroundImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        [self addSubview:backgroundImageView];
        [self addSubview:fileView];
        
        
    }
   if (self.style == CHBubbleStyleShke)
   {
      
   }
    if(self.isNotice && CHBubbleMessageTypeReceived == self.type){
        UIImage* image = [self foregroundIamge];
        self.foregroundImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        [self.foregroundImageView setImage:image];
        self.foregroundImageView.frame = self.backgroundImageView.frame;
        [self addSubview:self.foregroundImageView];
        [self bringSubviewToFront:self.foregroundImageView];
        
    }

    
}


-(UIImage*)foregroundIamge
{
    //   NSString *imgName = flag?(@"bubble-notice-received"):(@"bubble-default-received");
    
    NSString *imgName = @"bubble-notice-received";//flag?(@"bubble-default-received"):(@"bubble-default-received");
    UIImage * returnImage =  [[UIImage imageNamed:imgName] makeStretchableDefaultReceived];
    return returnImage;
}


-(void) setBubbleFrameWithSize:(CGSize) size
{
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, size.width, size.height);
    if (self.type == CHBubbleMessageTypeSended) {
        self.frame = CGRectMake(HARDWARE_SCREEN_WIDTH - kCHAvatarSize - 2*INSET_WIDTH - size.width, self.frame.origin.y, size.width, size.height);
    }
    self.voiceView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    [self.voiceView setImgVoiceOrigin];
    backgroundImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    if(self.foregroundImageView)self.foregroundImageView.frame = backgroundImageView.frame;
}

- (void)bubbleViewNeedResetFrameWithFrame:(CGRect)frame
{
    if (self.style == CHBubbleStyleVideo) {
        [self setVideoBubbleFrameWithSize:frame.size];
    }
    else
    {
    [self setImageBubbleFrameWithSize:frame.size];
    }
}
- (void)setVideoBubbleFrameWithSize:(CGSize) size
{
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, size.width + 4, size.height);
    if (self.type == CHBubbleMessageTypeSended) {
        self.frame = CGRectMake(HARDWARE_SCREEN_WIDTH - kCHAvatarSize - 2*INSET_WIDTH - size.width, self.frame.origin.y, size.width + 4, size.height);
    }
    videoView.frame = CGRectMake(2.0f, 0, size.width, size.height);
    if (self.type == CHBubbleMessageTypeSended) {
        videoView.frame = CGRectMake(0, 0, size.width, size.height);
    }
}
-(void)setImageBubbleFrameWithSize:(CGSize) size
{
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, size.width + 4, size.height);
    if (self.type == CHBubbleMessageTypeSended) {
        self.frame = CGRectMake(HARDWARE_SCREEN_WIDTH - kCHAvatarSize - 2*INSET_WIDTH - size.width, self.frame.origin.y, size.width + 4, size.height);
    }
    pictureView.frame = CGRectMake(2.0f, 0, size.width, size.height);
    if (self.type == CHBubbleMessageTypeSended) {
        pictureView.frame = CGRectMake(0, 0, size.width, size.height);
    }
    backgroundImageView.frame = CGRectMake(0, 0, size.width + 4, size.height);
    if(self.foregroundImageView)self.foregroundImageView.frame = backgroundImageView.frame;
}

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    backgroundImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
}

#pragma mark - Setters
- (void)setType:(CHBubbleMessageType)newType
{
    type = newType;
    [self setNeedsDisplay];
}

- (void)setStyle:(CHBubbleStyle)newStyle
{
    style = newStyle;
    [self setNeedsDisplay];
}

- (void)setText:(NSString *)newText
{
    text = newText;
    
    if (textLabel) {
        [textLabel removeFromSuperview];
    }
    
    CGFloat textLabelX = (self.type == CHBubbleMessageTypeSended)?(TEXTLABEL_MARGININSET1):(TEXTLABEL_MARGININSET2);
    
    CGSize textsize = [CBEmotionView getTextHeightWithEmotionString:newText maxWidth:BUBBLEVIEW_MAX_WIDTH];
    if (self.type == CHBubbleMessageTypeReceived) {
        textLabel = [[CBEmotionView alloc] initWithFrame:CGRectMake(textLabelX, kMarginTop, textsize.width, textsize.height)
                                           emotionString:newText
                                               textColor:[UIColor blackColor]];
//        窗口抖动的bug fixed by 李旭
        if (style == CHBubbleStyleShke) {
            UIImageView *shakeImageView = [[UIImageView alloc]initWithFrame:CGRectMake(textLabelX,kMarginTop, 30, textsize.height)];
            shakeImageView.image = [UIImage imageNamed:@"shakeicon"];
            [self addSubview:shakeImageView];

            textLabel = [[CBEmotionView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(shakeImageView.frame) + 10, kMarginTop, textsize.width, textsize.height)
                                               emotionString:newText
                                                   textColor:[UIColor grayColor]];
    }
        

    } else {
        textLabel = [[CBEmotionView alloc] initWithFrame:CGRectMake(textLabelX, kMarginTop, textsize.width, textsize.height)
                                           emotionString:newText
                                               textColor:[UIColor whiteColor]];

    }
    
    textLabel.backgroundColor = [UIColor clearColor];
    [self addSubview:textLabel];
    
    CGSize size = CGSizeMake(TEXTLABEL_MARGININSET1 + textsize.width + TEXTLABEL_MARGININSET2, textsize.height + kMarginTop + kMarginBottom);

    [self setFrame:CGRectMake(((self.type==CHBubbleMessageTypeSended)?( HARDWARE_SCREEN_WIDTH - kCHAvatarSize - 2*INSET_WIDTH - size.width):self.frame.origin.x),
                              self.frame.origin.y,
                              (NSInteger)(size.width),
                              size.height)];

    [backgroundImageView setFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
     if(self.foregroundImageView)self.foregroundImageView.frame = backgroundImageView.frame;
}

//- (void)setPicture:(UIImageView *)newPicture
//{
//    img_voice = newPicture;
//    [self setNeedsDisplay];
//}

- (void)setSelectedToShowCopyMenu:(BOOL)isSelected
{
    selectedToShowCopyMenu = isSelected;
    [self setNeedsDisplay];
}

#pragma mark - Drawing
- (CGRect)bubbleFrame
{
    CGSize bubbleSize = [CHBubbleView bubbleSizeForText:self.text];
    return CGRectMake((self.type == CHBubbleMessageTypeSended ? self.frame.size.width - bubbleSize.width : 0.0f),
                      0,
                      bubbleSize.width + 2*4,
                      bubbleSize.height + kMarginTop + kMarginBottom);
}

- (UIImage *)bubbleImageWithStyle:(CHBubbleStyle)bubbleStyle
{
    UIImage *returnImage = nil;
    if ((bubbleStyle == CHBubbleStyleText) || (bubbleStyle == CHBubbleStylePicture) || (bubbleStyle == CHBubbleStyleFile)) {
        returnImage = [CHBubbleView bubbleImageForTextAndPictureWithType:self.type isNotice:self.isNotice];
    }
    if (bubbleStyle == CHBubbleStyleVoice) {
        returnImage = [CHBubbleView bubbleImageForVoiceWithType:self.type isNotice:self.isNotice];
    }
    if (bubbleStyle == CHBubbleStyleRedPacket) {
        returnImage = [CHBubbleView bubbleImageForRedPacketWithType:self.type isNotice:self.isNotice];
    }
    return returnImage;
}
//UIEdgeInsetsMake(30.0f, 19.0f, 10.0f, 8.0f)
- (UIImage *)bubbleImageHighlighted
{
    return (self.type == CHBubbleMessageTypeReceived) ? [UIImage bubbleDefaultReceivedSelected] : [UIImage bubbleDefaultSendedSelected];
}

#pragma mark - Bubble view
+ (UIImage *)bubbleImageForTextAndPictureWithType:(CHBubbleMessageType)aType isNotice:(BOOL)flag
{
    UIImage *returnImage = nil;
    switch (aType) {
        case CHBubbleMessageTypeReceived:
        {
            //   NSString *imgName = flag?(@"bubble-notice-received"):(@"bubble-default-received");
            
            NSString *imgName = flag?(@"bubble-default-received"):(@"bubble-default-received");
            returnImage =  [[UIImage imageNamed:imgName] makeStretchableDefaultReceived];
            break;
        }
        case CHBubbleMessageTypeSended:
        {
            returnImage = [[UIImage imageNamed:@"bubble-default-sended"] makeStretchableDefaultSended];
            break;
        }
        default:
            break;
    }
    return returnImage;
}
+ (UIImage *)bubbleImageForRedPacketWithType:(CHBubbleMessageType)aType isNotice:(BOOL)flag
{
    UIImage *returnImage = nil;
    switch (aType)
    {
        case CHBubbleMessageTypeReceived:
        {
            //   NSString *imgName = flag?(@"bubble-notice-received"):(@"bubble-default-received");
            
            NSString *imgName = flag?(@"left"):(@"left");
            returnImage = [[UIImage imageNamed:imgName] makeStretchableDefaultReceived];
            returnImage = [returnImage stretchableImageWithLeftCapWidth:100 topCapHeight:40];

            break;
        }
        case CHBubbleMessageTypeSended:
        {
            returnImage = [[UIImage imageNamed:@"right"] makeStretchableDefaultSended]; //
             returnImage = [returnImage stretchableImageWithLeftCapWidth:100 topCapHeight:40];
            break;
        }
        default:
            break;
    }
    return returnImage;

}
+ (UIImage *)bubbleImageForVoiceWithType:(CHBubbleMessageType)aType isNotice:(BOOL)flag
{
    UIImage *returnImage = nil;
    switch (aType)
    {
        case CHBubbleMessageTypeReceived:
        {
         //   NSString *imgName = flag?(@"bubble-notice-received"):(@"bubble-default-received");
           
             NSString *imgName = flag?(@"bubble-default-received"):(@"bubble-default-received");
            returnImage = [[UIImage imageNamed:imgName] makeStretchableDefaultReceived]; //resizableImageWithCapInsets:UIEdgeInsetsMake(0, 19, 0, 8)
                                                          //             resizingMode:UIImageResizingModeStretch];
            break;
        }
        case CHBubbleMessageTypeSended:
        {
            returnImage = [[UIImage imageNamed:@"bubble-default-sended"] makeStretchableDefaultSended]; //resizableImageWithCapInsets:UIEdgeInsetsMake(0, 8, 0, 19)
                                                                                        //resizingMode:UIImageResizingModeStretch];
            break;
        }
        default:
            break;
    }
    return returnImage;
}

+ (UIFont *)font
{
    return [UIFont systemFontOfSize:16.0f];
}

+ (CGSize)bubbleSizeForText:(NSString *)txt
{
    CGSize returnSize = [CBEmotionView getTextHeightWithEmotionString:txt maxWidth:BUBBLEVIEW_MAX_WIDTH];
 
	return returnSize;
}

+ (CGFloat)cellHeightForText:(NSString *)txt
{
    return [CHBubbleView bubbleSizeForText:txt].height + kMarginTop + kMarginBottom;
}

//+ (int)maxCharactersPerLine
//{
//    return ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone) ? 33 : 109;
//}

//+ (int)numberOfLinesForMessage:(NSString *)txt
//{
//    return (txt.length / [CHBubbleView maxCharactersPerLine]) + 1;
//}

@end
